import { useState, memo, forwardRef, useImperativeHandle, useRef, useEffect } from 'react'
import { DatePicker } from 'antd'
import dayjs from 'dayjs'
import moment from 'moment'
import * as echarts from 'echarts'
import './index.scss'
const BarChart = forwardRef((props: any, ref: any) => {
    const { data = [], type = 1, title = "打印文件", year } = props
    const myChart = useRef<any>(null)
    const barRef = useRef<any>(null)
    const [defaultYear, setDefaultYear] = useState<string>(`${dayjs().year()}`)
    const handleYearChange = (val: any) => {
        const formatDate = val.format('YYYY')
        setDefaultYear(formatDate)
        year && year(formatDate)
    }
    const getLabel = (val: number) => {
        return val === 0
            ? "公开"
            : val === 1
                ? "内部"
                : val === 2
                    ? "秘密"
                    : val === 3
                        ? "机密"
                        : "绝密";
    }
    const initChart = async () => {
        await 1
        const res = [];
        for (let i = 0; i < 5; i++) {
            res.push({
                month: data.map((item: any) => {
                    const keys = Object.keys(item);
                    return item[(keys as any)]?.[i];
                }),
                label: getLabel(i),
            });
        }
        const colors = ["#EB7E66", "#FFAA00", "#7585A3", "#73DEB3", "#74A1FB", "#74A1FB"];
        const series = res.map((item, index) => {
            return {
                type: "bar",
                stack: "a",
                barWidth: 15,
                ...item,
                name: item.label,
                itemStyle: {
                    color: colors[index],
                },
                data: item.month,
            };
        });
        const stackInfo: any = {};
        for (let i = 0; i < series[0].data.length; ++i) {
            for (let j = 0; j < series.length; ++j) {
                const stackName = series[j].stack;
                if (!stackName) {
                    continue;
                }
                if (!stackInfo[stackName]) {
                    stackInfo[stackName] = {
                        stackStart: [],
                        stackEnd: [],
                    };
                }
                const info = stackInfo[stackName];
                const data = series[j].data[i];
                if (data && data !== "-") {
                    if (info.stackStart[i] == null) {
                        info.stackStart[i] = j;
                    }
                    info.stackEnd[i] = j;
                }
            }
        }
        for (let i = 0; i < series.length; ++i) {
            const { data } = series[i];

            const info = stackInfo[series[i].stack];
            for (let j = 0; j < series[i].data.length; ++j) {
                // const isStart = info.stackStart[j] === i;
                const isEnd = info.stackEnd[j] === i;
                const topBorder = isEnd ? 20 : 0;
                const bottomBorder = 0;
                data[j] = {
                    value: data[j],
                    itemStyle: {
                        borderRadius: [topBorder, topBorder, bottomBorder, bottomBorder],
                    },
                };
            }
        }
        const option = {
            grid: {
                top: "20%",
                bottom: "15%",
                left: 50,
                right: "5%",
            },
            tooltip: {
                show: true,
                trigger: "axis",
                formatter: (params: any) => {
                    const total = params.reduce((pre: number, newVal: any) => {
                        return pre + newVal.value;
                    }, 0);
                    let datastr = "";
                    params.forEach((item: any, index: number) => {
                        datastr += `<span style="margin-right: ${index % 2 == 1 ? "0px" : "15px"
                            };width: 80px">${item.seriesName}: ${item.value}  ${type === 1 ? "页" : "张"
                            }</span>`;
                    });
                    const html = `<div style="font-size: 12px;width: 180px">
                        <div class="flex-between">
                          <span style="color: #666;font-weight: 600">合计${total}${type === 1 ? "页" : "张"
                        }</span>
                          <span style="color: #ccc;margin-right: 10px;">
                            ${defaultYear}-${params[0].axisValue.padStart(2, "0")}
                          </span>
                        </div>
                        <div style="display: flex;width: 100%;flex-wrap: wrap;color: #ccc">
                          ${datastr}
                        </div>
  
                      </div>`;
                    return html;
                },
            },
            legend: {
                left: 0,
                top: 0,
                itemWidth: 10,
                itemHeight: 10,
                textStyle: {
                    color: "#999",
                },
            },
            xAxis: {
                type: "category",
                data: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
                axisLine: {
                    lineStyle: {
                        color: "#ccc",
                        type: "dashed",
                    },
                },
                axisTick: {
                    show: false,
                    alignWithLabel: true,
                },
            },
            yAxis: {
                type: "value",
                splitLine: {
                    show: true,
                    lineStyle: {
                        type: "dashed",
                        color: "#f1f1f1",
                    },
                },
            },
            series,
        };
        myChart.current.setOption(option);
    }
    useEffect(() => {
        myChart.current = echarts.init(barRef.current)
    }, [])
    useEffect(() => {
        initChart()
    }, [data])
    return (
        <>
            <div className="bar-chart">
                <div className="header flex-between">
                    <div className="title">
                        {title}
                        <span style={{ fontSize: '12px', fontWeight: 400 }}>({type === 1 ? "页" : "张"})</span>
                        <span style={{ fontSize: '12px', color: '#999', marginLeft: '8px' }}>按年统计</span>
                    </div>
                    <DatePicker
                        picker='year'
                        allowClear={false}
                        size="small"
                        defaultValue={moment(`${dayjs().year()}`, 'YYYY')}
                        onChange={handleYearChange}
                        format="yyyy年"
                        value-format="YYYY"
                        placeholder='请选择年份' style={{ marginLeft: '10px', width: '135px' }}></DatePicker>
                </div>
                <div className="chart" ref={barRef} style={{ height: 'calc(100% - 37px)' }}></div>
            </div>
        </>
    )
})
export default memo(BarChart)